package vh.sphynx.runtime.pattern;

import java.util.Map;

import vh.sphynx.runtime.impl.FindTextLocator;
import vh.sphynx.util.PatternMismatchedException;

public class CompositePatternMatchInfo extends PatternMatchInfo {

	public ITextLocator begin, end;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ITextLocator locate(int position, String pattern, int patternFlag, int operator, 
							boolean lastPosOnUnmatch, boolean optional, boolean excludeMatchedText, boolean throwException, Map groups) {
		CharSequence input = this.getLocalInput();
		int sidx = this.getPosition();
		ITextLocator locator = new FindTextLocator();
		int loc = locator.locate(input, sidx, pattern, patternFlag, operator, lastPosOnUnmatch, groups);
		if  (loc >= 0) {
			if (position == 1) { // begin
				this.setBeginLocation(excludeMatchedText ? loc + locator.getLength() : loc);
				// set the local position to the length of match text
				this.setPosition(locator.getLength(), IPatternMatchInfo.SEEK_LOCAL_FROM_BEGIN);
			}
			else 
				this.setEndLocation( excludeMatchedText ? loc : loc + locator.getLength());
		}
		else if (!optional) {
			this.setMatched(false);
			if (throwException)
				throw new PatternMismatchedException(context, null, String.format("Unable to locate '%s' in the input", pattern));
		}
		if (position == 1)
			begin = locator;
		else
			end = locator;
		return loc >= 0 ? locator : null;
	}

	public ITextLocator getBegin() {
		return begin;
	}

	public ITextLocator getEnd() {
		return end;
	}

}
